// pages/orderDetail/orderDetail.js
import {
  unified_order,
  get_open_id
} from '../../utils/api.js'
import {
  MD5
} from '../../utils/MD5.js'
var haveTap = 1; // 1: 可以点击 0：不可点击
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    objectArray: [],
    index: 0,
    index1: 0,
    items: [],
    addr: {},
    orderInfo: {},
    goodsInfo: [],
    deliveryShow: false,
    code_btn: '关闭',
    company: '',
    company_code: '',
    express_num: ''
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this;
    var objectArray = that.data.objectArray;
    this.setData({
      index: e.detail.value,
      index1: 1,
      company: objectArray[e.detail.value].name,
      company_code: objectArray[e.detail.value].code,
    })
    console.log(this.data.objectArray[e.detail.value]);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  // 复制到剪贴版
  copyToCli: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success(res) {
        app.showTipMsg('复制到剪贴板')
      }
    })
  },
  // 
  close_code: function() {
    this.setData({
      deliveryShow: false
    });
  },
  company_input: function(e) {
    var that = this;
    var company = e.detail.value;

    if (company != '') {
      that.setData({
        code_btn: '确定',
        company: company
      });
    }
  },
  express_num_input: function(e) {
    var that = this;
    var express_num = e.detail.value;

    if (express_num != '') {
      that.setData({
        code_btn: '确定',
        express_num: express_num
      });
    }
  },
  sureCode: function() {
    const that = this
    var company = that.data.company;
    var company_code = that.data.company_code;
    var express_num = that.data.express_num;
    if (company == '') {
      wx.showToast({
        title: '物流公司必填!',
        icon: 'none',
        duration: 1000
      })
    } else if (express_num == '') {
      wx.showToast({
        title: '快递单号必填!',
        icon: 'none',
        duration: 1000
      })
    } else {
      wx.showLoading({
        title: '加载中',
      })
      // console.log(company);
      // console.log(express_num);
      var url2 = '/user_api/editExpress';
      var params2 = {
        order_id: that.data.order_id,
        company: company,
        company_code: company_code,
        express_num: express_num,
        sn: that.data.orderInfo.sn,
        uid: that.data.orderInfo.uid,
      };
      app.HttpPostSend(url2, params2, function(res) {
        wx.hideLoading();

        if (res.code > 0) {
          wx.showModal({
            title: '提示',
            content: '发货成功',
            showCancel: false,
            success: function(res) {
              var str = "orderInfo.status";
              var str_company = "orderInfo.company";
              var str_express_num = "orderInfo.express_num";
              that.setData({
                deliveryShow: false,
                [str]: 3,
                [str_company]: company,
                [str_express_num]: express_num
              });
              var pages = getCurrentPages(); //页面指针数组 
              var prepage = pages[pages.length - 2]; //上一页面指针 
              var orderlist = that.data.orderlist;
              var str_order = orderlist + '[' + that.data.idx + '].status';
              var number = prepage.data.tabs[1].text;
              var number2 = prepage.data.tabs[2].text;
              number = parseInt(number) - 1;
              number2 = parseInt(number2) + 1;
              var str_num = 'tabs[1].text';
              var str_num2 = 'tabs[2].text';
              prepage.setData({
                [str_order]: 3,
                [str_num]: number,
                [str_num2]: number2
              }); //操作上一页面 
              wx.navigateBack({
                delta: 1,
              }); //返回上一页面
            },
          })

        }

      });
    }



  },
  sureCode1: function() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '确认用户已提货?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          var url2 = '/user_api/editExpress1';
          var params2 = {
            order_id: that.data.order_id,
            sn: that.data.orderInfo.sn,
            uid: that.data.orderInfo.uid,
          };
          app.HttpPostSend(url2, params2, function(res) {
            wx.hideLoading();

            if (res.code > 0) {
              wx.showModal({
                title: '提示',
                content: '发货成功',
                showCancel: false,
                success: function(res) {
                  var str = "orderInfo.status";
                  that.setData({
                    deliveryShow: false,
                    [str]: 3
                  });
                  var pages = getCurrentPages(); //页面指针数组 
                  var prepage = pages[pages.length - 2]; //上一页面指针 
                  var orderlist = that.data.orderlist;
                  var str_order = orderlist + '[' + that.data.idx + '].status';
                  var number = prepage.data.tabs[1].text;
                  var number2 = prepage.data.tabs[2].text;
                  number = parseInt(number) - 1;
                  number2 = parseInt(number2) + 1;
                  var str_num = 'tabs[1].text';
                  var str_num2 = 'tabs[2].text';
                  prepage.setData({
                    [str_order]: 3,
                    [str_num]: number,
                    [str_num2]: number2
                  }); //操作上一页面 
                  wx.navigateBack({
                    delta: 1,
                  }); //返回上一页面
                },
              })

            }

          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  onLoad: function(options) {
    var order_group_id = 0;
    if (options.order_group_id != undefined) {
      order_group_id = options.order_group_id;
    }
    var id = options.id;
    var that = this;
    var url2 = '/order/details';
    var params2 = {
      id: id,
      order_group_id: order_group_id
    };
    that.setData({
      
      // activeIndex: options.activeIndex
    })
    app.HttpPostSend(url2, params2, function(res) {
      // console.log(res)
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        if (res.data) {
          var orderInfo = res.data.orderInfo;

          var goodsInfo = res.data.goodsInfo;
          for (var i = 0; i < goodsInfo.length; i++) {
            goodsInfo[i].title = goodsInfo[i].title.slice(0, 12);
          }

          that.setData({
            order_id: orderInfo.id,
            idx: options.idx,
            orderlist: options.orderlist,
            orderInfo: orderInfo,
            goodsInfo: goodsInfo,
            spec_price_name: res.data.spec_price_name,
            objectArray: res.data.express_code
          })
        }
      }
    });
  },
  checkUserInfo: function () {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function (result_data) {
          if (result_data === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                userInfo: result_data.data,
                u_id: app.globalData.userInfo.id
              })

            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function (result) {

                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;

                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        authSettingUser: 0,
                        openid: result.data.openid.openid
                      })

                    }
                  }, 1)
                }
              })
            }
          }
        })
    } else {

      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function (result) {

            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {

              app.globalData.openid = result.data.openid.openid;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                authSettingUser: 0,
                openid: result.data.openid.openid
              })

            }
          }, 1)
        },
        fail: function (res) {
          console.log('失败');
        }
      })
    }

  },
  //点击进入详情页面
  bindGoodsTap: function(e) {
    var id = e.detail.button_typId;
    var title = e.detail.button_status;
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?id=' + id + '&title=' + title,
    })
  },

  bindEditTap: function(e) {
    wx.navigateTo({
      url: '../myAddress/myAddress?goodsId=' + this.data.goodsId + '&mount=' + this.data.mount,
    })
  },
  // 退换
  bindtuih: function(e) {
    if (haveTap == 0) {
      console.log('屏蔽重复点击')
    } else {
      haveTap == 0
      var that = this;
      wx.showModal({
        title: '提示',
        content: '确定同意吗?',
        success(res) {
          if (res.confirm) {
            var status = 0;
            var refund_type = e.currentTarget.dataset.refund_type;
            if (refund_type == 0 || refund_type == 1) {
              refund_type = 1;
              status = 5;
            } else {
              refund_type = 2;
              status = 3;
            }
            var url2 = '/user_api/order_refund';
            var params2 = {
              id: e.currentTarget.dataset.refund_id,
              sn: e.currentTarget.dataset.sn,
              uid: e.currentTarget.dataset.uid,
              refund_type: refund_type,

            };

            app.HttpPostSend(url2, params2, function(res) {
              // console.log(res)
              wx.showModal({
                title: '提示',
                content: res.data.status,
                showCancel: false,
                success: function(re) {
                  if (res.code > 0) {
                    var str = "orderInfo.status";
                    that.setData({
                      [str]: status
                    });
                    var pages = getCurrentPages(); //页面指针数组 
                    var prepage = pages[pages.length - 2]; //上一页面指针 
                    var orderlist = that.data.orderlist;
                    var str_order = orderlist + '[' + that.data.idx + '].status';
                    var str_order_refund = orderlist + '[' + that.data.idx + '].goods_info[' + e.currentTarget.dataset.idx + '].refund_ing';

                    prepage.setData({
                      [str_order]: status,
                      [str_order_refund]: 1
                    }); //操作上一页面 
                    wx.navigateBack({
                      delta: 1,
                    });
                  }

                },
              })
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  //点击提醒发货
  tishiSent: function(e) {
    var id = e.currentTarget.dataset.id;
    var mgid = e.currentTarget.dataset.mgid;
    var order_group_id = e.currentTarget.dataset.order_group_id;
    app.showTipMsg('已提醒!');
    // 发送模板消息-访客到访通知
    app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 9, '', '', order_group_id, '', '', mgid);
  },
  //点击查看订单详情
  showOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id=' + id,
    })
  },

  //点击确认收货
  sureGet: function(e) {
    var id = e.currentTarget.dataset.id;
    var url2 = '/order/updateOrderStatus_v4';
    var params2 = {
      id: id,
      type: 4,
      invite_id: app.globalData.shareOptions.share_id,
      invite_uid: app.globalData.shareOptions.carte_id,
      timestamp: new Date().getTime(),
    };
    params2.sign = app.getSign(params2)
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {

        // 发送模板消息-确认收货通知
        // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 6, '/radarPages/radarCenter/radarCenter', id, '', '', '')

        wx.navigateTo({
          url: '/pages/myOrders/myOrders'
        })
      }
    });
  },
  //点击去评价
  pingjOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/shopPages/Publication/Publication?order_id=' + id,
    })
  },
  //点击删除订单
  deleteOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    var url2 = '/order/updateOrderStatus_v4';
    var params2 = {
      id: id,
      type: 7,
      invite_id: app.globalData.shareOptions.share_id,
      invite_uid: app.globalData.shareOptions.carte_id,
      timestamp: new Date().getTime(),
    };
    params2.sign = app.getSign(params2)
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        wx.navigateTo({
          url: '/pages/myOrders/myOrders'
        })
      }
    });
  },
  //点击申请售后
  applyGoods: function(e) {
    wx.showModal({
      title: '提示',
      content: '请确认该订单申请售后',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 6,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              wx.navigateTo({
                url: '/pages/myOrders/myOrders'
              })
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 点击联系客服进去咨询页面
  bindGoSocksTap: function(e) {
    wx.navigateTo({
      url: '../socks/socks',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  toGoodsDetail: function(e) {
    wx.navigateTo({
      url: "/pages/goodsDetail/goodsDetail?id=" + e.currentTarget.dataset.id
    })
  },
  delivery: function(e) {
    var order_id = e.currentTarget.dataset.order_id;
    this.setData({
      deliveryShow: true
    });
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})